package com.reguang.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reguang.mapper.SysMenuMapper;
import com.reguang.mapper.SysRoleMapper;
import com.reguang.mapper.SysUserRoleMapper;
import com.reguang.pojo.SysRoleDO;
import com.reguang.pojo.SysRoleMenuDO;
import com.reguang.service.SysRoleService;

@Service
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Autowired
	private SysMenuMapper sysMenuMaper;

	@Override
	public SysRoleDO queryOne(SysRoleDO record) {
		return roleMapper.selectOne(record);
	}

	@Override
	public PageInfo<SysRoleDO> list(Map<String, Object> params) {
		// 设置分页
		PageHelper.startPage(Integer.parseInt(params.get("offset").toString()),
				Integer.parseInt(params.get("limit").toString()));
		List<SysRoleDO> list = roleMapper.select(null);
		PageInfo<SysRoleDO> infoList = new PageInfo<SysRoleDO>(list);
		return infoList;
	}

	@Override
	public SysRoleDO queryByPrimaryKey(Integer id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	/**
	 * 保存新增角色和关联菜单信息 role.getMenuIds() 为关联菜单的信息
	 */
	@Override
	public Integer save(SysRoleDO role) {
		Integer[] menuIds = role.getMenuIds();
		Integer row = roleMapper.insertUseGeneratedKeys(role);
		if (row > 0) {
			for (int i = 0; i < menuIds.length; i++) {
				SysRoleMenuDO sysRoleMenuDo = new SysRoleMenuDO(role.getId() + "", menuIds[i] + "");
				sysMenuMaper.insertSysRoleMenuInfo(sysRoleMenuDo);
			}
		}
		return row;
	}

	/**
	 * 保存修改 角色和关联关系
	 */
	@Override
	public Integer update(SysRoleDO role) {
		Integer[] menuIds = role.getMenuIds();
		Integer row = roleMapper.updateByPrimaryKey(role);
		
		if (row > 0) {
			int deleteRows=sysMenuMaper.deleteSysRoleMenuInfoByRoleId(role.getId());
			for (int i = 0; i < menuIds.length; i++) {
				SysRoleMenuDO sysRoleMenuDo = new SysRoleMenuDO(role.getId() + "", menuIds[i] + "");
				sysMenuMaper.insertSysRoleMenuInfo(sysRoleMenuDo);
			}
		}
		return row;
	}

	@Override
	public Integer deleteById(Integer id) {
		int deleteRows=sysMenuMaper.deleteSysRoleMenuInfoByRoleId(id);
		return roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<SysRoleDO> getAllRoles() {
		return roleMapper.selectAll();
	}

	@Override
	public List<SysRoleDO> queryListByUserId(String id) {
		List<String> rolesIds = sysUserRoleMapper.listRoleId(id);
		List<SysRoleDO> roles = this.getAllRoles();
		for (SysRoleDO roleDO : roles) {
			roleDO.setSign("false");
			for (String roleId : rolesIds) {
				if (Objects.equals(roleDO.getId(), roleId)) {
					roleDO.setSign("true");
					break;
				}
			}
		}
		return roles;
	}

}
